#include "chinactptraderthread.h"

#include <QDebug>
#include <QDateTime>
#include <QString>
ChinaCtpTraderThread::ChinaCtpTraderThread(QObject *parent) : QThread(parent){

}

ChinaCtpTraderThread::~ChinaCtpTraderThread() {
    stopMd();
}

QString ChinaCtpTraderThread::getOrderRef() {
    QDateTime currentDateTime = QDateTime::currentDateTime();
    orderRefID = orderRefID+1;
    return QStringLiteral("%1%2").arg(currentDateTime.toString("ddHHmm")).arg(orderRefID, 7, 10, QChar('0'));
}

// 启动行情服务（在主线程调用）
void ChinaCtpTraderThread::startMd(const QString &frontAddr,const QString brokerID,const QString inventorID,const QString password,const QString appID,const QString authCode) {
    m_frontAddr = frontAddr;
    mBrokerID = brokerID;
    mInventorID = inventorID;
    mPassword = password;
    mAppID = appID;
    mAuthCode = authCode;
    if (!isRunning()) {
        m_running = true;
        start();  // 启动线程（调用run()）
    }
}

// 停止行情服务
void ChinaCtpTraderThread::stopMd() {
    // 3. 退出线程事件循环
    m_running = false;
    if (m_mdApi) {
        qDebug() << "ChinaCtpTraderThread 开始退出任务" << currentThreadId();
        //m_mdApi->Join(); // 等待API内部线程结束
        m_mdApi->Release();  // 释放API资源
        m_mdApi = nullptr;
        qDebug() << "ChinaCtpTraderThread 完成处理退出任务" << currentThreadId();
    }
    // 2. 释放SPI对象
    if (m_mdSpi) {
        delete m_mdSpi;
        m_mdSpi = nullptr;
    }
    quit();
    qDebug() << "ChinaCtpTraderThread 退出任务成功" << currentThreadId();
}
// 撤单
void ChinaCtpTraderThread::revokeOrder(const QString symbol,const QString orderID) {
    m_mdSpi->reqOrderAction(symbol.toUtf8().data(),orderID.toUtf8().data());

}
// 开单
void ChinaCtpTraderThread::openBuyOrder(const QString exchange,const QString symbol,const int quatity,const double openPrice) {
    if (m_mdSpi) {
        bool isCloseOrder = false;
        bool isBuyOrder = true;
        m_mdSpi->reqOrderInsert(
            getOrderRef().toUtf8().data(),
            exchange.toUtf8().data(),
            symbol.toUtf8().data(),
            openPrice,
            quatity,
            isCloseOrder,
            isBuyOrder
        );
    }


}

void ChinaCtpTraderThread::openSellOrder(const QString exchange,const QString symbol,const int quatity,const double openPrice) {
    if (m_mdSpi) {
        bool isCloseOrder = false;
        bool isBuyOrder = false;
        m_mdSpi->reqOrderInsert(
            getOrderRef().toUtf8().data(),
            exchange.toUtf8().data(),
            symbol.toUtf8().data(),
            openPrice,
            quatity,
            isCloseOrder,
            isBuyOrder
            );
    }

}

void ChinaCtpTraderThread::closeSellOrder(const QString exchange,const QString symbol,const int quatity,const double openPrice,const bool isTodayOrder) {
    if (m_mdSpi) {
        bool isCloseOrder = true;
        bool isBuyOrder = false;
        m_mdSpi->reqOrderInsert(
            getOrderRef().toUtf8().data(),
            exchange.toUtf8().data(),
            symbol.toUtf8().data(),
            openPrice,
            quatity,
            isCloseOrder,
            isBuyOrder,
            isTodayOrder
        );
    }

}

void ChinaCtpTraderThread::closeBuyOrder(const QString exchange,const QString symbol,const int quatity,const double openPrice,const bool isTodayOrder) {
    if (m_mdSpi) {
        bool isCloseOrder = true;
        bool isBuyOrder = true;
        m_mdSpi->reqOrderInsert(
            getOrderRef().toUtf8().data(),
            exchange.toUtf8().data(),
            symbol.toUtf8().data(),
            openPrice,
            quatity,
            isCloseOrder,
            isBuyOrder,
            isTodayOrder
        );
    }
}

void ChinaCtpTraderThread::reqAccountData() {
}

void ChinaCtpTraderThread::reqPosition() {
}

void ChinaCtpTraderThread::reqPositionDetail() {
}

void ChinaCtpTraderThread::reqTraderByToday() {
}

void ChinaCtpTraderThread::reqTranferByToday() {
}
// 线程入口（独立线程中运行）
void ChinaCtpTraderThread::run() {
    //qDebug() << "行情线程启动，线程ID：" << currentThreadId();

    // 创建API实例（必须在当前线程中创建）
    m_mdApi = CThostFtdcTraderApi::CreateFtdcTraderApi();
    qDebug() << "CThostFtdcTraderApi GetApiVersion" << m_mdApi->GetApiVersion();

    // 创建回调实例
    m_mdSpi = new ChinaCtpTrader(m_mdApi,mBrokerID.toUtf8().data(),mInventorID.toUtf8().data(),mPassword.toUtf8().data(),mAppID.toUtf8().data(),mAuthCode.toUtf8().data());

    // 注册回调接口
    m_mdApi->RegisterSpi(m_mdSpi);

    m_mdApi->RegisterFront((char*)m_frontAddr.toUtf8().data());

    // 初始化API
    m_mdApi->Init();

    // 转发信号（回调中不能直接操作UI，通过信号到主线程）
    //connect(m_mdSpi, &ChinaCtpTrader::connected, this, &ChinaCtpTraderThread::connected);
    //connect(m_mdSpi, &ChinaCtpTrader::disconnected, this, &ChinaCtpTraderThread::disconnected);
    //connect(m_mdSpi, &ChinaCtpTrader::loginResult, this, &ChinaCtpTraderThread::loginResult);
    //connect(m_mdSpi, &ChinaCtpTrader::tradeDataReceived, this, &ChinaCtpTraderThread::tradeDataReceived);

    // 线程循环（保持线程运行）
    exec();  // 启动事件循环

    // 清理资源
    delete m_mdSpi;
    m_mdSpi = nullptr;
}
